const app = getApp();
var openId = null
let jinbiShareLgImg = ''
let jinbiShareMinImg = ''
let jinbiShareText = ''
Page({
  data: {
    jinbi: 0,
    xianjin: 0,
    jinbiShow: false,
    my_moreJinbi: false,
  },
  //异步获取系统控制变量
  getSystemController() {
    if (app.globalData.controller == null) {
      app.getSystemController().then(res => {
        this.setData({
          my_moreJinbi: res.my_moreJinbi,
          jinbiShow: res.jinbiShow
        })
      })
    } else {
      this.setData({
        my_moreJinbi: app.globalData.controller.my_moreJinbi,
        jinbiShow: app.globalData.controller.jinbiShow
      })
    }
  },
  // 加载顶部多媒体展示到页面
  selectTopImg() {
    if (app.globalData.getGlobalShareMedia == null) {
      app.getGlobalShareMedia().then(res => {
        jinbiShareLgImg = res.jinbiShareLgImg
        jinbiShareMinImg = res.jinbiShareMinImg
        jinbiShareText = res.jinbiShareText
      })
    } else {
      jinbiShareLgImg = app.globalData.getGlobalShareMedia.jinbiShareLgImg,
        jinbiShareMinImg = app.globalData.getGlobalShareMedia.jinbiShareMinImg,
        jinbiShareText = app.globalData.getGlobalShareMedia.jinbiShareText
    }
  },
  onShow() {
    this.tabBar()
    this.selectUser() // 查询金币数量并显示
  },
  onLoad() {
    if(!app.globalData.isRegistered){
      app.selecteUser().then(res=>{
        app.globalData.isRegistered = res
      })
    }
    this.getMyJinBiNum() // 获取我的金币数量并保存到全局变量
    this.getSystemController() //异步获取系统控制变量
    this.selectTopImg() // 加载顶部多媒体展示到页面
  },
  // 获取我的金币数量并保存到全局变量
  getMyJinBiNum() {
    if (app.globalData.userInfo) {
      openId = app.globalData.userInfo._openid
      this.setData({
        jinbi: app.globalData.userInfo.jinbiNum,
        xianjin: app.globalData.userInfo.jinbiNum / 10,
      })
    }else{
      this.selectUser()
    }
  },
  // 查询金币数量并显示
  selectUser() {
    wx.cloud.callFunction({
      name: 'user',
      data: {
        tag: 'selecteUser'
      }
    }).then(res => {
      openId = res.result[0]._openid
      this.setData({
        jinbi: res.result[0].jinbiNum,
        xianjin: res.result[0].jinbiNum / 10
      })
    })
  },
  // 兑换
  duihuan() {
    wx.navigateTo({
      url: `/pages/my_tixian/my_tixian?jinbi=${this.data.jinbi}`,
    })
  },
  // 更多金币平台
  moreJinbi() {
    wx.navigateToMiniProgram({
      appId: 'wx83ed21db6ad34120',
      path: 'page/index/index?tag=moreJinbi',
      extraData: {
        foo: 'bar'
      },
      envVersion: 'release',
      success(res) {
        // 打开成功
      }
    })
  },

  tabBar() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      })
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: jinbiShareText,
      path: `/pages/news/news?shangjiOpenId=${app.globalData.userInfo._openid}`,
      imageUrl: jinbiShareLgImg,
    }
  },

})